<template>
  <div class="role-container">
    <eForm ref="form" :is-add="isAdd"/>
    <div class="head-container">
      <el-input
        clearable
        placeholder="输入角色名称搜索"
        size="mini"
        style="width: 200px;"
        class="filter-item"
      />
      <el-button class="filter-item" size="mini" type="success" icon="el-icon-search">搜索</el-button>
      <!-- 新增 -->
      <div style="display: inline-block;margin: 0px 2px;">
        <el-button
          class="filter-item"
          size="mini"
          type="primary"
          icon="el-icon-plus"
          @click="add"
        >新增</el-button>
      </div>
    </div>
    <el-row :gutter="15">
      <!--角色管理-->
      <el-col :xs="24" :sm="24" :md="16" :lg="16" :xl="17">
        <el-card class="box-card" shadow="never">
          <div slot="header" class="clearfix">
            <span class="role-span">角色列表</span>
            <div id="opt" style="float: right">
              <el-radio-group v-model="opt" size="mini">
                <el-radio-button label="菜单分配"/>
                <el-radio-button label="权限分配"/>
              </el-radio-group>
            </div>
          </div>
          <el-table
            v-loading="loading"
            :data="roles"
            highlight-current-row
            size="small"
            style="width: 100%;"
            border
            @current-change="currentChange"
          >
            <el-table-column prop="role" label="名称"/>
            <el-table-column :show-overflow-tooltip="true" prop="roleName" label="描述"/>
            <el-table-column label="操作" align="center">
              <template slot-scope="scope">
                <el-button size="mini" type="primary" icon="el-icon-edit" @click="edit(scope.row)"/>
                <el-popover :ref="scope.row.id" placement="top" width="180">
                  <p>确定删除本条数据吗？</p>
                  <div style="text-align: right; margin: 0">
                    <el-button size="mini" type="text" @click="$refs[scope.row.uuid].doClose()">取消</el-button>
                    <el-button
                      :loading="delLoading"
                      type="primary"
                      size="mini"
                      @click="remove(scope.row.uuid)"
                    >确定</el-button>
                  </div>
                  <el-button slot="reference" type="danger" size="mini" icon="el-icon-delete"/>
                </el-popover>
              </template>
            </el-table-column>
          </el-table>
          <!--分页组件-->
          <el-pagination
            style="margin-top:20px"
            background
            layout="prev, pager, next"
            :page-count="total"
            @current-change="pageChange"
          />
        </el-card>
      </el-col>
      <!-- 授权 -->
      <el-col :xs="24" :sm="24" :md="8" :lg="8" :xl="7">
        <el-card v-show="opt === '菜单分配'" v-loading="mpLoading" class="box-card" shadow="never">
          <div slot="header" class="clearfix">
            <el-tooltip class="item" effect="dark" content="选择指定角色分配菜单" placement="top">
              <span class="role-span">菜单分配</span>
            </el-tooltip>
            <el-button
              :disabled="!showButton"
              :loading="menuLoading"
              icon="el-icon-check"
              size="mini"
              style="float: right; padding: 6px 9px"
              type="primary"
              @click="saveMenu"
            >保存</el-button>
          </div>
          <el-tree
            ref="menu"
            :data="menus"
            :default-checked-keys="menuIds"
            :props="menuProps"
            accordion
            show-checkbox
            node-key="uuid"
          />
        </el-card>
        <el-card v-show="opt === '权限分配'" v-loading="mpLoading" class="box-card" shadow="never">
          <div slot="header" class="clearfix">
            <el-tooltip class="item" effect="dark" content="选择指定角色分配权限" placement="top">
              <span class="role-span">权限分配</span>
            </el-tooltip>
            <el-button
              :disabled="!showButton"
              :loading="permissionLoading"
              icon="el-icon-check"
              size="mini"
              style="float: right; padding: 6px 9px"
              type="primary"
              @click="savePermission"
            >保存</el-button>
          </div>
          <el-tree
            ref="permission"
            :data="permissions"
            :default-checked-keys="permissionIds"
            :props="permissionProps"
            show-checkbox
            accordion
            node-key="uuid"
          />
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import eForm from './form';
import {
  role_page,
  permission_all,
  menu_all,
  role_bind_permission,
  role_bind_menu,
  role_menu,
  role_remove,
  role_permission
} from '@/api/system';
import Menu from '@/utils/menu';
export default {
  components: { eForm },
  data() {
    return {
      roles: [],
      isAdd: false,
      total: 0,
      menuProps: {
        children: 'children',
        label: 'name'
      },
      permissionProps: {
        children: 'children',
        label: 'permissionName'
      },
      currentId: 0,
      permissionLoading: false,
      menuLoading: false,
      mpLoading: false,
      showButton: false,
      opt: '菜单分配',
      delLoading: false,
      permissions: [],
      permissionIds: [],
      menus: [],
      menuIds: []
    };
  },
  created() {
    this.getRoles(0);
    this.getPermissions();
    this.getMenus();
  },
  methods: {
    async getRoles(page) {
      this.loading = true;
      const res = await role_page({
        page: page,
        pageSize: 10
      });
      this.roles = res.data.pageData;
      this.total = res.data.total;
      if (!this.roles.length) this.showButton = false;
      this.loading = false;
    },
    async getPermissions() {
      this.permissionLoading = true;
      const res = await permission_all();
      this.permissions = res.data;
      this.permissionLoading = false;
    },
    async getMenus() {
      this.menuLoading = true;
      const res = await menu_all();
      this.menus = Menu.convertTree(res.data);
      this.menuLoading = false;
    },
    pageChange(value) {
      console.log(value);
    },
    async currentChange(val) {
      if (val) {
        this.mpLoading = true;
        this.$refs.permission.setCheckedKeys([]);
        this.$refs.menu.setCheckedKeys([]);
        this.currentId = val.uuid;
        this.showButton = true;
        this.menuIds = [];
        this.permissionIds = [];
        const [menus, permissions] = await Promise.all([
          role_menu(val.uuid, {
            uuid: val.uuid
          }),
          role_permission(val.uuid, {
            uuid: val.uuid
          })
        ]);
        this.menuIds = menus.data.reduce((i, c) => {
          i.push(c.uuid);
          return i;
        }, []);
        this.permissionIds = permissions.data.reduce((i, c) => {
          i.push(c.uuid);
          return i;
        }, []);
        this.mpLoading = false;
      }
    },
    async savePermission() {
      try {
        this.permissionLoading = true;
        const role = {
          roleUuid: this.currentId,
          actionIds: this.$refs.permission.getCheckedKeys()
        };
        await role_bind_permission(role);
        this.$message({
          message: '保存成功',
          type: 'success'
        });
        this.permissionLoading = false;
      } catch (error) {
        this.permissionLoading = false;
      }
    },
    async saveMenu() {
      try {
        this.menuLoading = true;
        const role = {
          roleUuid: this.currentId,
          menuUuids: [
            ...this.$refs.menu.getCheckedKeys(),
            ...this.$refs.menu.getHalfCheckedNodes()
          ]
        };

        await role_bind_menu(role);
        this.$message({
          message: '保存成功',
          type: 'success'
        });
        this.menuLoading = false;
      } catch (error) {
        this.menuLoading = false;
      }
    },
    add() {
      this.isAdd = true;
      this.$refs.form.dialog = true;
    },
    edit(data) {
      this.isAdd = false;
      const _this = this.$refs.form;
      _this.form = {
        uuid: data.uuid,
        role: data.role,
        roleName: data.roleName
      };
      _this.dialog = true;
    },
    async remove(id) {
      try {
        this.delLoading = true;
        await role_remove(id);
        this.$message({
          type: 'success',
          message: '删除成功'
        });
        this.delLoading = false;
        this.getRoles(0);
      } catch (error) {
        this.delLoading = false;
      }
    }
  }
};
</script>

<style rel="stylesheet/scss" lang="scss">
.role-span {
  font-weight: bold;
  color: #303133;
  font-size: 15px;
}
.head-container {
  margin-bottom: 20px;
}
</style>
